package com.czl.module_storehouse.activity.allocate.post;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.czl.base.data.bean.tengyun.LocatListBean;
import com.czl.base.data.bean.tengyun.ProductBean;
import com.czl.base.data.bean.tengyun.SortBean;
import com.czl.base.util.SpHelper;
import com.czl.module_base.http.HttpResponse;
import com.czl.module_base.mvp.presenter.InjectPresenter;
import com.czl.module_base.utils.ParcelHelper;
import com.czl.module_service.system.Constants;
import com.czl.module_storehouse.R;
import com.czl.module_storehouse.activity.base.BaseOperationActivity;
import com.czl.module_storehouse.activity.intostore.saveloc.SaveLocActivity;
import com.czl.module_storehouse.activity.managegoods.add.GoodsAddActivity;
import com.czl.module_storehouse.adapter.AllocatePostInAdapter;
import com.czl.module_storehouse.adapter.BaseNumAdapter;
import com.czl.module_storehouse.bean.AllocateBean;
import com.czl.module_storehouse.bean.AllocateInBean;
import com.czl.module_storehouse.databinding.ActivityBaseOperationBinding;
import com.czl.module_storehouse.databinding.HeaderAllocatePostOutBinding;
import com.czl.module_storehouse.event.AllocateEvent;
import com.czl.module_storehouse.event.AllocatePostInEvent;
import com.czl.module_storehouse.event.AllocatePostInSortEvent;
import com.czl.module_storehouse.event.AllocateScanBackEvent;
import com.czl.module_storehouse.event.AllocateSortEvent;
import com.czl.module_storehouse.event.SaveLocationEvent;
import com.czl.module_storehouse.event.SortEvent;
import com.czl.module_storehouse.mvp.presenter.AllocatePresenter;
import com.czl.module_storehouse.mvp.view.AllocateView;
import com.czl.module_base.widget.timeselector.TimeSelector;
import com.jeremyliao.liveeventbus.LiveEventBus;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author xubin
 */
public class AllocatePostInActivity extends BaseOperationActivity<ActivityBaseOperationBinding> implements AllocateView {

    private AllocateBean mAllocateBean;
    private BaseNumAdapter<SortBean> mAdapter;
    private final AllocateInBean allocateInBean = new AllocateInBean();
    private boolean mIsInCompany;
    private HeaderAllocatePostOutBinding mHeaderBinding;

    @InjectPresenter
    AllocatePresenter mAllocatePresenter;

    @Override
    protected ActivityBaseOperationBinding getBinding(LayoutInflater layoutInflater) {
        return ActivityBaseOperationBinding.inflate(layoutInflater);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        mHeaderBinding = HeaderAllocatePostOutBinding.inflate(getLayoutInflater());
        EventBus.getDefault().register(this);
        super.initData(savedInstanceState);
        mToolBinding.toolbarContentTitle.setText("调拨入库");
        binding.btnSure.setText("调拨入库");
        binding.recyclerView.setAdapter(getAdapter());
    }

    @Override
    protected void loadData() {
        super.loadData();
        if (!mIsInCompany && mAllocateBean != null) {
            mAllocatePresenter.getNeedDealtMoveNewSortInfo(mAllocateBean.getMoveId());
        }
    }

    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void onDataEvent(SortEvent sortEvent) {
        if (sortEvent != null && mAdapter != null) {
            SortBean sortBean = sortEvent.getSortBean();
            SortBean item = mAdapter.getItem(mSelectedPosition);
            item.setInSortId(sortBean.getInSortId());
            getAdapter().setData(mSelectedPosition, item);
        }
    }

    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void onDataEvent(AllocateEvent event) {
        if (event != null && event.getAllocateBean() != null) {
            AllocateBean allocateBean = event.getAllocateBean();
            mAllocateBean = ParcelHelper.copy(allocateBean);
            mIsInCompany = mAllocateBean.isInCompany();
            allocateInBean.setMoveId(mAllocateBean.getMoveId());
            allocateInBean.setInCompany(mIsInCompany);
            getAdapter().setList(mAllocateBean.getSortList());
            setMoveData();
            initHeaderView(mAllocateBean);
        }
    }

    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void onDataEvent(AllocateScanBackEvent event) {
        SortBean sortBean = event.getSortBean();
        getAdapter().setData(mSelectedPosition, sortBean);
        binding.btnSure.setEnabled(getLocationCount(sortBean) > 0);
    }

    public int getLocationCount(SortBean sortBean) {
        if (sortBean.getLocatList() == null || sortBean.getLocatList().size() == 0) {
            return 0;
        }
        int count = 0;
        int defaultNum = 0;
        int sortCount = 0;
        for (LocatListBean bean : sortBean.getLocatList()) {
            List<ProductBean> productList = bean.getProductList();
            if (productList != null && !productList.isEmpty()) {
                count += productList.size();
            } else {
                if (bean.getStorehouseLocatId() == SpHelper.INSTANCE.decodeInt(Constants.SpKey.STOREHOUSE_LOCATION_NAME)) {
                    //默认仓位
                    defaultNum = bean.getStockNumInt();
                }
                sortCount += bean.getStockNumInt();
                count += bean.getStockNumInt();
            }
        }
        sortBean.setLocatTotalNum(sortCount - defaultNum);
        return count;
    }

    @SuppressLint("SetTextI18n")
    public void initHeaderView(AllocateBean allocateBean) {
        mHeaderBinding.clHeaderInfo.ivHeader.setImageResource(R.mipmap.icn_idx_lingyong);
        if (allocateBean == null) {
            return;
        }
        mHeaderBinding.clHeaderInfo.tvHeaderTitle.setText(allocateBean.getMoveName());
        mHeaderBinding.clHeaderInfo.tvHeaderCode.setText("调拨单：" + (allocateBean.getMoveCode() == null ? "" : allocateBean.getMoveCode()));
        mHeaderBinding.clHeaderInfo.tvHeaderDate.setText(allocateBean.getGmtCreate());
        mHeaderBinding.tvHeaderCompany.setText("申请公司：" + (allocateBean.getApplyCompanyName() == null ? "" : allocateBean.getApplyCompanyName()));
        mHeaderBinding.tvHeaderDepartment.setText("申请部门：" + (allocateBean.getApplyPersonDepartment() == null ? "" : allocateBean.getApplyPersonDepartment()));
        mHeaderBinding.tvStoreOut.setText("调出仓库：" + (allocateBean.getMoveStorehouseName() == null ? "" : allocateBean.getMoveStorehouseName()));
        mHeaderBinding.tvStoreIn.setText("调入仓库：" + (allocateBean.getInStorehouseName() == null ? "" : allocateBean.getInStorehouseName()));
        mHeaderBinding.tvReason.setText("调拨原因：" + (allocateBean.getApplyComment() == null ? "" : allocateBean.getApplyComment()));
        mHeaderBinding.tvOutCompany.setText("调出公司：" + (allocateBean.getMoveCompanyName() == null ? "" : allocateBean.getMoveCompanyName()));
    }

    private void setMoveData() {
        allocateInBean.setMoveSortViewList(mAllocateBean.getMoveSortViewList());
        allocateInBean.setMoveProductViewList(mAllocateBean.getMoveProductViewList());
        allocateInBean.setInStorehouseId(mAllocateBean.getInStorehouseId());
    }

    private void onItemClickData(View itemView, int position) {
        mSelectedPosition = position;
        SortBean item = mAdapter.getItem(position);
        int id = itemView.getId();
        if (id == R.id.iv_right || id == R.id.tv_product_loc) {
            if (!item.getExistCompanyBol(mIsInCompany)) {
                showToast("请先创建物品");
                return;
            }
            goLocActivity(item);
        } else if (id == R.id.tv_date) {
            if (!item.getExistCompanyBol(mIsInCompany)) {
                showToast("请先创建物品");
                return;
            }
            if (itemView instanceof TextView) {
                TextView textView = (TextView) itemView;
                showTimeSelector(textView, item::setManufactureDate);
            }
        } else if (id == R.id.tv_add_goods) {
            goAddGoodsActivity(item);
        }
    }

    private void showTimeSelector(TextView textView, TimeSelector.ResultHandler resultHandler) {
        TimeSelector timeSelector = new TimeSelector(this, time ->
        {
            textView.setText(time);
            resultHandler.handle(time);
        }, "1990-01-01", "2099-12-31", TimeSelector.FORMAT_STR2, new Date());
        timeSelector.setScrollUnit(TimeSelector.SCROLLTYPE.YEAR,
                TimeSelector.SCROLLTYPE.MONTH,
                TimeSelector.SCROLLTYPE.DAY);
        timeSelector.show();
    }

    @Override
    protected void startActivity(int position, View view) {
        onItemClickData(view, position);
        super.startActivity(position, view);
    }

    private void goAddGoodsActivity(SortBean item) {
        AllocateSortEvent sortEvent = new AllocateSortEvent();
        sortEvent.setSortBean(item);
        EventBus.getDefault().postSticky(sortEvent);
        startActivity(new Intent(getContext(), GoodsAddActivity.class));
    }

    /**
     * 选择位置
     *
     * @param sortBean
     */
    private void goLocActivity(SortBean sortBean) {
        if (sortBean == null) {
            return;
        }
        if (1 == sortBean.manageMode() && mIsInCompany && sortBean.pasteCode()) {
            AllocatePostInSortEvent event = new AllocatePostInSortEvent(sortBean, null);
            LiveEventBus.get(AllocatePostInSortEvent.class).postDelay(event, 200);
            event.setAllocate(mAllocateBean);
            startActivity(new Intent(getContext(), AllocateScanActivity.class));
        } else {
            //选择调拨物品存放位置
            SaveLocationEvent event = new SaveLocationEvent(sortBean, getMaxNum(sortBean));
            EventBus.getDefault().postSticky(event);
            startActivity(new Intent(getContext(), SaveLocActivity.class));
        }
    }

    @Override
    protected BaseQuickAdapter<SortBean, ?> getAdapter() {
        if (mAdapter == null) {
            mAdapter = new AllocatePostInAdapter(R.layout.item_allocate_post_in, new ArrayList<>(), mIsInCompany);
            mAdapter.addHeaderView(mHeaderBinding.getRoot());
            addFooterView(mAdapter);
            mAdapter.setOnItemChildClickListener((adapter, view, position) -> onItemClickData(view, position));
            mAdapter.setOnNumChangeListener(count -> setButtonState());
        }
        return mAdapter;
    }

    @Override
    protected Button getButton() {
        return binding.btnSure;
    }

    @Override
    protected String getOperationTitle() {
        return "调拨";
    }

    @Override
    protected int getMaxNum(SortBean sortBean) {
        return sortBean.getAllocatedInNum();
    }

    @Override
    protected void submit() {
        String remark = mFooterBinding.etRemark.getText().toString();
        allocateInBean.setInComment(remark);
        allocateInBean.setSortList(mAdapter.getData());
        if (mAllocatePresenter != null) {
            mAllocatePresenter.moveStorage(allocateInBean);
        }
    }

    @Override
    public <T> void showHttpResponse(HttpResponse<T> httpResponse) {
        super.showHttpResponse(httpResponse);
        if (AllocatePresenter.TAG_ALLOCATE_MOVE_STORAGE.equals(httpResponse.getRequestTag())) {
            showToast("调拨成功");
            EventBus.getDefault().postSticky(new AllocatePostInEvent());
            finish();
        } else if (AllocatePresenter.TAG_NEED_DEALT_MOVE_NEW_SORT_INFO.equals(httpResponse.getRequestTag())) {
            Object data = httpResponse.getData();
            if (data == null) {
                return;
            }
            if (data instanceof AllocateBean) {
                mAllocateBean = (AllocateBean) data;
                mAdapter.setList(mAllocateBean.getSortList());
                setMoveData();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mHeaderBinding != null) {
            mHeaderBinding.unbind();
        }
    }
}
